package com.dbs.task.async;

import java.util.Random;
import java.util.concurrent.Future;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

/**
 * 异步调用 启动类也需要加入@EnableAsync 不能对多个异步调用进行封装 例如这里的test()，封装的话controll层调用就会变成同步
 * 只能在想调用的方法中调用多个异步任务
 * 
 * @author dongbisheng
 * @date Apr 14, 2017 10:48:14 AM
 */
@Component
public class AsyncTask {
	public static Random random = new Random();

	// @Async所修饰的函数不要定义为static类型，这样异步调用不会生效
	// 异步回调,使用Future<T>来返回异步调用的结果
	@Async
	public Future<String> doTaskOne() throws Exception {
		System.out.println("开始做任务一");
		long start = System.currentTimeMillis();
		Thread.sleep(5000);
		long end = System.currentTimeMillis();
		System.out.println("完成任务一，耗时：" + (end - start) + "毫秒");
		return new AsyncResult<>("任务一完成");
	}

	@Async
	public Future<String> doTaskTwo() throws Exception {
		System.out.println("开始做任务二");
		long start = System.currentTimeMillis();
		Thread.sleep(5000);
		long end = System.currentTimeMillis();
		System.out.println("完成任务二，耗时：" + (end - start) + "毫秒");
		return new AsyncResult<>("任务二完成");
	}

	@Async
	public Future<String> doTaskThree() throws Exception {
		System.out.println("开始做任务三");
		long start = System.currentTimeMillis();
		Thread.sleep(5000);
		long end = System.currentTimeMillis();
		System.out.println("完成任务三，耗时：" + (end - start) + "毫秒");
		return new AsyncResult<>("任务三完成");
	}

	/*
	 * public String test() throws Exception { long start =
	 * System.currentTimeMillis(); Future<String> task1 = doTaskOne();
	 * Future<String> task2 = doTaskTwo(); Future<String> task3 = doTaskThree();
	 * while (true) { if (task1.isDone() && task2.isDone() && task3.isDone()) {
	 * // 三个任务都调用完成，退出循环等待 break; } Thread.sleep(1000); } long end =
	 * System.currentTimeMillis(); System.out.println("任务全部完成，总耗时：" + (end -
	 * start) + "毫秒"); return ("任务全部完成，总耗时：" + (end - start) + "毫秒"); }
	 */
}
